package com.jyxd.web.service.assessment.basic;

import com.jyxd.web.dao.basic.CommonSettingDao;
import com.jyxd.web.data.basic.CommonSetting;
import com.jyxd.web.data.basic.QuartzTask;
import com.jyxd.web.data.basic.QuartzTime;
import com.jyxd.web.data.dto.HttpResult;
import com.jyxd.web.data.user.User;
import com.jyxd.web.task.NursingVitalSignsJob;
import com.jyxd.web.task.QuartzSchedulerUtil;
import com.jyxd.web.task.VitalSignsJob;
import com.jyxd.web.util.CronUtil;
import com.jyxd.web.util.DateUtil;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.jyxd.web.config.ConstantConfig.COMMON_SETTING_IS_MERGE_FORM;
import static com.jyxd.web.util.ExecuteUtil.errorIfEmpty;
import static com.jyxd.web.util.UUIDUtil.getUUID;

@Service
@Transactional
public class CommonSettingService {

    @Autowired
    private CommonSettingDao commonSettingDao;
    @Autowired
    private QuartzTaskService quartzTaskService;


    //定义一个成员变量
    private static QuartzTask quartzTask;

    public boolean insert(CommonSetting commonSetting) {
        return commonSettingDao.insert(commonSetting);
    }

    public boolean update(CommonSetting commonSetting) {
        return commonSettingDao.update(commonSetting);
    }

    public CommonSetting queryData(String id) {
        return commonSettingDao.queryData(id);
    }

    public List<CommonSetting> queryList(Map<String, Object> map) {
        return commonSettingDao.queryList(map);
    }

    public int queryNum(Map<String, Object> map) {
        return commonSettingDao.queryNum(map);
    }

    /**
     * 查询排班时间的通用设置列表
     *
     * @param map
     * @return
     */
    public List<CommonSetting> getSchedualTimeList(Map<String, Object> map) {
        return commonSettingDao.getSchedualTimeList(map);
    }

    /**
     * 系统设置--通用设置--监护仪采集频率/默认首页--查询监护仪频率或默认首页
     *
     * @param map
     * @return
     */
    public List<CommonSetting> getCommonSettingByType(Map<String, Object> map) {
        return commonSettingDao.getCommonSettingByType(map);
    }

    /**
     * 根据病人id查询护理文书同步设置
     *
     * @param map
     * @return
     */
    public List<CommonSetting> getCommonSettingByPatientId(Map<String, Object> map) {
        return commonSettingDao.getCommonSettingByPatientId(map);
    }


    /**
     * 更新自动同步开关
     *
     * @param commonSetting
     * @return
     */
    public boolean updateOnOrOff(CommonSetting commonSetting) {
        boolean flag = false;
        QuartzTime quartzTime = new QuartzTime();
        quartzTime.setStartTime(new Date());
        flag = commonSettingDao.updateOnOrOff(commonSetting);//修改记录表中自动同步的打开或关闭
        QuartzSchedulerUtil qsu = new QuartzSchedulerUtil();
        SchedulerFactory schedulerFactoryBean = new StdSchedulerFactory();

        if (flag == true) {
            if (commonSetting.getOnOff().equals("0")) {//打开
                /**
                 * 查询对应记录的频率，转换为cron表达式，启动定时任务,
                 */
                CommonSetting common = commonSettingDao.queryData(commonSetting.getId());
                String cron = CronUtil.createLoopCronExpression(1, Integer.valueOf(common.getSettingContent()));
                System.out.println(CronUtil.createLoopCronDescription(1, Integer.valueOf(common.getSettingContent())));

                Map<String, Object> map = new HashMap<>();
                map.put("jobName", "VitalSignsJob");
                map.put("jobGroup", "VitalSignsJob");
                quartzTask = quartzTaskService.queryDataByNameAndGroup(map);

                if (quartzTask == null) {
                    //如果为空 说明数据库中没有这个任务 需要添加
                    QuartzTask data = new QuartzTask();
                    data.setId(getUUID());
                    data.setCreateTime(new Date());
                    data.setCron(cron);
                    data.setDescription("定时同步生命体征");
                    data.setJobGroup("VitalSignsJob");
                    data.setJobName("VitalSignsJob");
                    data.setStatus(1);
                    data.setTaskName("VitalSignsJob");
                    data.setType("系统任务");
                    quartzTaskService.insert(data);
                } else {
                    QuartzTask data = new QuartzTask();
                    data.setJobName("VitalSignsJob");
                    data.setStatus(1);
                    data.setCron(cron);
                    quartzTaskService.updateBySelect(data);
                }


                try {
                    Scheduler scheduler = schedulerFactoryBean.getScheduler();
                    // 通过JobBuilder构建JobDetail实例，JobDetail规定只能是实现Job接口的实例
                    // JobDetail 是具体Job实例

                    JobDetail jobDetail = JobBuilder.newJob(VitalSignsJob.class).withIdentity("VitalSignsJob", "VitalSignsJob").build();
                    // 基于表达式构建触发器
                    CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(cron);
                    // CronTrigger表达式触发器 继承于Trigger
                    // TriggerBuilder 用于构建触发器实例
                    CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity("VitalSignsJob", "VitalSignsJob")
                            .withSchedule(cronScheduleBuilder).build();
                    JobKey jobKey = new JobKey("VitalSignsJob", "VitalSignsJob");
                    JobDetail job = scheduler.getJobDetail(jobKey);
                    if (job != null) {
                        scheduler.deleteJob(jobKey);
                    }
                    scheduler.scheduleJob(jobDetail, cronTrigger);
                    scheduler.start();


                } catch (SchedulerException e) {
                    e.printStackTrace();
                }
            } else {
                try {
                    Scheduler scheduler = schedulerFactoryBean.getScheduler();
                    qsu.pauseJob("VitalSignsJob", "VitalSignsJob", scheduler);
                    qsu.deleteJob("VitalSignsJob", "VitalSignsJob", scheduler);
                    System.out.println("停止同步");
                } catch (SchedulerException e) {
                    e.printStackTrace();
                }
            }

        }
        return flag;

    }


    /**
     * 护理文书生命体征同步开关
     *
     * @param commonSetting
     * @return
     */
    public boolean NursingUpdateOnOrOff(CommonSetting commonSetting, User user) {
        boolean flag = false;
        QuartzTime quartzTime = new QuartzTime();
        quartzTime.setStartTime(new Date());
        flag = commonSettingDao.updateOnOrOff(commonSetting);//修改记录表中自动同步的打开或关闭
        QuartzSchedulerUtil qsu = new QuartzSchedulerUtil();
        SchedulerFactory schedulerFactoryBean = new StdSchedulerFactory();
        if (flag == true) {
            if (commonSetting.getOnOff().equals("0")) {//打开
                Map<String, Object> map = new HashMap<>();
                map.put("jobName", "NursingVitalSignsJob");
                map.put("jobGroup", "NursingVitalSignsJob");
                quartzTask = quartzTaskService.queryDataByNameAndGroup(map);

                if (quartzTask == null) {
                    //如果为空 说明数据库中没有这个任务 需要添加
                    QuartzTask data = new QuartzTask();
                    data.setId(getUUID());
                    data.setCreateTime(new Date());
                    data.setCron(commonSetting.getSettingContent());
                    data.setDescription("护理文书同步生命体征");
                    data.setJobGroup("NursingVitalSignsJob");
                    data.setJobName("NursingVitalSignsJob");
                    data.setStatus(1);
                    data.setTaskName("NursingVitalSignsJob");
                    data.setType("系统任务");
                    quartzTaskService.insert(data);
                } else {
                    QuartzTask data = new QuartzTask();
                    data.setJobName("NursingVitalSignsJob");
                    data.setStatus(1);
                    data.setCron(commonSetting.getSettingContent());
                    quartzTaskService.updateBySelect(data);
                }
                try {
                    Map<String, String> selectmap = new HashMap<>();
                    JobDetail detail = JobBuilder.newJob(NursingVitalSignsJob.class).withIdentity("NursingVitalSignsJob")
                            .build();


                    // 创建一个Trigger实例，定义该job立即执行，并且在每隔2秒重复执行
                    Trigger trigger = TriggerBuilder
                            .newTrigger()
                            .startAt(DateUtil.yyyyMMddHHmmssSdfToDate(commonSetting.getBeginTime()))
                            .endAt(DateUtil.yyyyMMddHHmmssSdfToDate(commonSetting.getEndTime()))
                            .withSchedule(
                                    SimpleScheduleBuilder.simpleSchedule()
                                            .withIntervalInSeconds(Integer.valueOf(commonSetting.getSettingContent()) * 60).repeatForever())
                            .build();

                    selectmap.put("patientId", commonSetting.getPatientId());
                    selectmap.put("id", commonSetting.getId());

                    detail.getJobDataMap().put("map", selectmap);
                    detail.getJobDataMap().put("user", user);


                    SchedulerFactory factory = new StdSchedulerFactory();
                    Scheduler scheduler = factory.getScheduler();


                    if (scheduler.checkExists(detail.getKey())) {
                        scheduler.deleteJob(detail.getKey());
                    }

                    scheduler.start();
                    // 把jobDetail和Trigger与scheuler绑定在一起：触发启动
                    scheduler.scheduleJob(detail, trigger);
                } catch (SchedulerException e) {
                    e.printStackTrace();
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            } else {
                try {
                    Scheduler scheduler = schedulerFactoryBean.getScheduler();
                    qsu.pauseJob("NursingVitalSignsJob", "NursingVitalSignsJob", scheduler);
                    qsu.deleteJob("NursingVitalSignsJob", "NursingVitalSignsJob", scheduler);
                    System.out.println("停止同步");
                    commonSettingDao.updateOnOrOff(commonSetting);
                } catch (SchedulerException e) {
                    e.printStackTrace();
                }
            }

        }
        return flag;

    }

    /**
     * 修改同步新旧表单标志接口
     *
     * @return
     */
    public HttpResult updateFormSign(Map<String, Object> map) {
        errorIfEmpty(map, "参数不能为空");
        errorIfEmpty(map.get("settingType"), "通用标识type不能为空");
        errorIfEmpty(map.get("settingContent"), "通用设置值不能为空");
        List<CommonSetting> settingList = getCommonSettingByType(map);
        if (CollectionUtils.isEmpty(settingList)) {
            CommonSetting commonSetting = new CommonSetting();
            commonSetting.setId(getUUID());
            commonSetting.setSettingType(COMMON_SETTING_IS_MERGE_FORM);
            commonSetting.setCreateTime(new Date());
            commonSetting.setSettingName("通用设置使用新旧表单全局标识");
            commonSetting.setSettingContent((String) map.get("settingContent"));
            insert(commonSetting);
            return new HttpResult(200, "通用设置全局标识新增成功");
        }
        CommonSetting commonSetting = settingList.get(0);
        commonSetting.setSettingContent((String) map.get("settingContent"));
        update(commonSetting);
        return new HttpResult(200, "通用设置全局标识修改成功");
    }


}
